package com.lt.test.provider.service;

import com.lt.test.api.RedisService;
import com.lt.test.api.RoleService;
import com.lt.test.common.constant.RedisConstant;
import com.lt.test.common.exception.CustomException;
import com.lt.test.entity.DO.RoleDO;
import com.lt.test.entity.DTO.CustomRole;
import com.lt.test.entity.DTO.PageDTO;
import com.lt.test.entity.QueryModel.PageFilter;
import com.lt.test.entity.QueryModel.PageQueryModel;
import com.lt.test.provider.mapper.RoleMapper;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * Created by zhengchuan on 2017/3/27.
 */
@Service("roleService")
public class RoleServiceImpl implements RoleService {

    @Resource
    private RoleMapper roleMapper;
    @Resource
    private RedisService redisService;

    @Override
    public String getRoleForSelect() throws CustomException {
        try {
             List<RoleDO> roleDOs  = roleMapper.getRoleForSelect();
            StringBuilder builder = new StringBuilder();
            builder.append("<select>");
            for (RoleDO role : roleDOs) {
                builder.append("<option value='" + role.getId() + "'>" + role.getRoleName() + "</option>");
            }
            builder.append("</select>");
            return builder.toString();
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取角色列表用来展示失败");
        }
    }

    @Override
    public List getRoleForList() throws CustomException {
        try {
            List<RoleDO> roleDOs  = roleMapper.getRoleForSelect();
            return roleDOs;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取角色列表用来展示失败");
        }
    }

    @Override
    public PageDTO<CustomRole> findUserByPage(Integer page, Integer pageSize, String sortedKey, String sortedValue, String filters)  throws CustomException {
        Long beginNum = (long) ((page - 1) * pageSize + 1);
        Long endNum = beginNum + pageSize - 1;

        PageQueryModel pageQueryModel = new PageQueryModel();
        pageQueryModel.setBeginNum(beginNum);
        pageQueryModel.setEndNum(endNum);

        if("gmtCreateStr".equals(sortedKey)) {
            pageQueryModel.setSortName("R.GMT_CREATE");
        }else {
            pageQueryModel.setSortName("R.GMT_MODIFIED");
        }
        pageQueryModel.setSortOrder(("asc".equals(sortedValue) ? "asc" : "desc"));//防止sql注入

        if(filters != null && !filters.trim().equals("")) {
            JSONObject jsonObject = JSONObject.fromObject(filters);
            JSONArray jsonArray = (JSONArray) jsonObject.get("rules");
            List<PageFilter> filterList = new ArrayList<>();
            for(int i = 0; i < jsonArray.size(); i++) {
                JSONObject result = (JSONObject) jsonArray.get(i);
                if("username".equals(result.get("field")) && StringUtils.isNotBlank(result.getString("data"))){
                    PageFilter filter = new PageFilter();
                    filter.setFilterName("R.ROLE_NAME");
                    filter.setFilterType("LIKE");
                    filter.setFilterValue("'%"+result.getString("data")+"%'");
                    filterList.add(filter);
                }
               /* if("phone".equals(result.get("field")) && StringUtils.isNotBlank(result.getString("data"))){
                    PageFilter filter = new PageFilter();
                    filter.setFilterName("U.PHONE");
                    filter.setFilterType("LIKE");
                    filter.setFilterValue("'%"+result.getString("data")+"%'");
                    filterList.add(filter);
                }*/
            }
            pageQueryModel.setFilters(filterList);
        }
        List<CustomRole> userList = null;
        int recordCount = 0;
        try {
            userList = roleMapper.findRoleByPage(pageQueryModel);
            recordCount = roleMapper.getRoleCount(pageQueryModel);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取角色列表失败");
        }
        PageDTO<CustomRole> result = new PageDTO<>(page, pageSize, userList, recordCount);
        return result;
    }

    @Override
    public RoleDO findRoleByRoleKey(String roleKey) throws CustomException {
        try {
            return roleMapper.findRoleByRoleKey(roleKey);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("根据key获取角色失败");
        }
    }

    @Override
    public RoleDO findRoleByRoleName(String roleName) throws CustomException {
        try {
            return roleMapper.findRoleByRoleName(roleName);
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("根据name获取角色失败");
        }
    }

    @Override
    public void editRoleInfo(CustomRole role, String oper) throws CustomException {
        role.setDelete(role.getState().equals("0") ? false : true);
        role.setGmtModified(new Date());
        switch (oper) {
            case "edit":
                if(role.getId() == null) {
                    throw new CustomException("更新角色信息没有主键");
                }
                try {
                    roleMapper.editRoleInfo(role);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new CustomException("更新角色信息失败");
                }
                break;
            case "add" :
                role.setId(UUID.randomUUID().toString().replace("-", "").toUpperCase());
                role.setGmtCreate(new Date());
                try {
                    roleMapper.insertRole(role);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new CustomException("添加角色失败");
                }
                break;
            default:
                throw new CustomException("不知道操作类型");
        }
    }

    @Override
    public List<Map<String, Object>> getPrivilegesByRoleId(String roleId) throws CustomException {
        List<Map<String, Object>> result;
        try {
            result = roleMapper.getPrivilegesByRoleId(roleId);
            for (Map<String, Object> privilege : result) {
                if (privilege.get("checked") != null) {
                    privilege.put("checked" , true);
                    privilege.put("open" , true);
                }else {
                    privilege.put("checked" , false);
                    privilege.put("open" , false);
                }
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            throw new CustomException("获取权限树失败");
        }

    }

    @Override
    public void roleAuthorization(String roleId, String[] checkedNode, String[] cancelCheckedNode) throws CustomException {
        if (checkedNode.length > 0) {
            Map<String,Object> checkedNodeObj  = new HashMap(2,1.0F);
            checkedNodeObj.put("roleId", roleId);
            checkedNodeObj.put("checkedNodes", checkedNode);
            try {
                roleMapper.doRoleAuthorization(checkedNodeObj);
            } catch (Exception e) {
                e.printStackTrace();
                throw new CustomException("添加权限失败");
            }
        }
        if (cancelCheckedNode.length > 0) {
            Map<String,Object> cancelCheckedNodeObj  = new HashMap(2,1.0F);
            cancelCheckedNodeObj.put("roleId", roleId);
            cancelCheckedNodeObj.put("cancelCheckedNodes", cancelCheckedNode);
            try {
                roleMapper.doCancelRoleAuthorization(cancelCheckedNodeObj);
            } catch (Exception e) {
                e.printStackTrace();
                throw new CustomException("删除权限失败");
            }
        }
        String redisRoleKey = RedisConstant.PLATFORM_PERMISSION_KRY_PRE+roleId;
        boolean isSuccess = redisService.del(redisRoleKey);
        if (!isSuccess) {
            throw new CustomException("删除权限缓存失败，roleId："+roleId);
        }
    }
}
